package cloud.xiguapi.ubas.analysis.uv;

import cloud.xiguapi.ubas.analysis.uv.model.SetUvCountResult;
import cloud.xiguapi.ubas.analysis.uv.model.UVResult;
import cloud.xiguapi.ubas.model.UserBehavior;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;
import org.apache.flink.streaming.api.functions.timestamps.BoundedOutOfOrdernessTimestampExtractor;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.concurrent.TimeUnit;

import static cloud.xiguapi.ubas.constant.JobNameConstant.SET_UV;

/**
 * @author 大大大西西瓜皮🍉
 * date: 2021-5-19 上午 09:33
 * desc:
 */
@Component
public class SetUVAnalysis {

    @Resource(name = "env")
    private StreamExecutionEnvironment env;

    @Async("setUVAnalysis")
    public void analysis(String path) throws Exception {
        env.setParallelism(8);
        env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);

        // 读取数据
        DataStream<String> inputDataStream = env.readTextFile(path);

        // 转换为Java Bean, 并分配时间戳和水印
        DataStream<UserBehavior> userBehaviorDataStream = inputDataStream.map(line -> {
            String[] fields = line.split(",");
            return UserBehavior.builder()
                    .userId(Long.valueOf(fields[0]))
                    .itemId(Long.valueOf(fields[1]))
                    .categoryId(Long.valueOf(fields[2]))
                    .behavior(fields[3])
                    .timestamp(Long.valueOf(fields[4]))
                    .build();
        }).assignTimestampsAndWatermarks(new BoundedOutOfOrdernessTimestampExtractor<UserBehavior>(
                Time.of(200, TimeUnit.MILLISECONDS)) {
            @Override
            public long extractTimestamp(UserBehavior element) {
                return element.getTimestamp() * 1000L;
            }
        });

        // 开窗统计UV值
        SingleOutputStreamOperator<UVResult> uvResultDataStream = userBehaviorDataStream.filter(data -> "pv".equals(data.getBehavior()))
                .timeWindowAll(Time.hours(1L))
                .apply(new SetUvCountResult());

        uvResultDataStream.print();
        uvResultDataStream.addSink(new SetUVMySqlSink());

        env.execute(SET_UV.getJobName());
    }

    public static class SetUVMySqlSink extends RichSinkFunction<UVResult> {

        private transient Connection connection;

        private transient PreparedStatement clearStatement;

        private transient PreparedStatement selectStatement;

        private transient PreparedStatement insertStatement;

        private transient PreparedStatement updateStatement;

        private transient boolean isFirst = true;

        @Override
        public void open(Configuration parameters) throws Exception {
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/ubas?serverTimezone=UTC", "root", "1015");
            clearStatement = connection.prepareStatement("TRUNCATE TABLE set_uv");
            selectStatement = connection.prepareStatement("SELECT 1 FROM set_uv WHERE window_end = ? LIMIT 1");
            insertStatement = connection.prepareStatement("INSERT INTO set_uv(window_end, cnt) VALUES(?, ?)");
            updateStatement = connection.prepareStatement("UPDATE set_uv SET cnt = ? WHERE window_end = ?");
        }

        @Override
        public void close() throws Exception {
            updateStatement.close();
            selectStatement.close();
            clearStatement.close();
            insertStatement.close();
            connection.close();
        }

        @Override
        public void invoke(UVResult value, SinkFunction.Context context) throws Exception {
            if (isFirst) {
                clearStatement.execute();
                isFirst = false;
                return;
            }

            selectStatement.setString(1, value.getWindowEnd());
            boolean next = selectStatement.executeQuery().next();

            if (next) {
                updateStatement.setLong(1, value.getCount());
                updateStatement.setString(2, value.getWindowEnd());
                updateStatement.execute();
            } else {
                insertStatement.setString(1, value.getWindowEnd());
                insertStatement.setLong(2, value.getCount());
                insertStatement.execute();
            }
        }
    }
}
